package com.vanzo.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.vanzo.adapter.MemberListRecyclerAdapter;
import com.vanzo.bean.MembersListBeen;
import com.vanzo.encryption.R;
import com.vanzo.interfaces.OnRecyclerViewItemClickListener;
import com.vanzo.view.ButtonListener;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by tisen on 2018/1/4.
 */

public class TalkieFragment extends BaseFragment implements View.OnClickListener, OnRecyclerViewItemClickListener {

    private static final int CHANGER_CURRENT_CODE = 0;
    private RecyclerView mRecyclerView;
    private RelativeLayout mTalkieFollowersTitle;
    private ImageView mKeyboardDownOrUp;
    private TextView mMemberListTitle;
    private List<MembersListBeen> mMemberLists;
    private MemberListRecyclerAdapter mAdapter;
    private ImageView mAddMumber;
    private int nunber;
    private UiHandler mUiHandler;
    private TextView mCurrentCode;

    @Override
    protected int getFragmentLayoutId() {
        return R.layout.fragment_talkie;
    }

    @Override
    protected void initView(View view) {
        if (view == null) {
            return;
        }
        TextView mTitle = (TextView) view.findViewById(R.id.tv_title);
        mTitle.setText("对讲");

        mTalkieFollowersTitle = (RelativeLayout) view.findViewById(R.id.talkie_followers_title);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.talkie_followers_recycle);
        mKeyboardDownOrUp = (ImageView) view.findViewById(R.id.iv_keyboard_down_up);
        mMemberListTitle = (TextView) view.findViewById(R.id.tv_member_list_title);
        mAddMumber = (ImageView) view.findViewById(R.id.iv_right);
        mAddMumber.setVisibility(View.VISIBLE);

        ButtonListener mTalkieButton = (ButtonListener) view.findViewById(R.id.talkie_button);
    }

    @Override
    protected void initListener() {
        mAddMumber.setOnClickListener(this);
        mTalkieFollowersTitle.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        mMemberLists = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            MembersListBeen membersListBeen = new MembersListBeen();
            if (i == 0) {
                membersListBeen.setName("本组");
            } else {
                membersListBeen.setName("00" + i);
            }

            mMemberLists.add(membersListBeen);
        }
        mMemberListTitle.setText("成员列表(" + mMemberLists.size() + ")");
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new MemberListRecyclerAdapter(getActivity(), mMemberLists);
        mRecyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.talkie_followers_title:
                if (mRecyclerView.getVisibility() == View.GONE) {
                    mKeyboardDownOrUp.setImageDrawable(getResources().getDrawable(R.mipmap.ic_keyboard_arrow_down_white_24dp));
                    mRecyclerView.setVisibility(View.VISIBLE);
                } else {
                    mKeyboardDownOrUp.setImageDrawable(getResources().getDrawable(R.mipmap.ic_keyboard_arrow_up_white_24dp));
                    mRecyclerView.setVisibility(View.GONE);
                }
                break;

            case R.id.iv_right:
                showPopupWindow();
                break;
        }
    }


    @Override
    public void onItemClick(View view, int position) {
        Toast.makeText(getActivity(), "点击", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDelete(int position) {
        if (mMemberLists != null && mMemberLists.size() != 0) {
            showDialog(position);
        }
    }

    @Override
    public void onMessage(int position) {
        if (mMemberLists != null && mMemberLists.size() != 0) {
            Intent intent = new Intent(getActivity(), ChatDetailsActivity.class);
            intent.putExtra("currentChat", mMemberLists.get(position).getName());
            getActivity().startActivity(intent);
        }
    }

    @Override
    public void onTalkie(int position) {
        if (mMemberLists != null && mMemberLists.size() != 0) {
            Toast.makeText(getActivity(), "信息 : " + mMemberLists.get(position).getName(), Toast.LENGTH_SHORT).show();
        }
    }



    private void showPopupWindow() {
        // 用于PopupWindow的View
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popupwindow_add_mumber, null, false);
        final PopupWindow window = new PopupWindow(contentView, ViewPager.LayoutParams.MATCH_PARENT, ViewPager.LayoutParams.WRAP_CONTENT, true);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        window.setOutsideTouchable(false);
        window.setFocusable(true);
        window.showAtLocation(getView(), Gravity.CENTER, 0, 0);
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        EditText mGroupNumber = (EditText) contentView.findViewById(R.id.ed_group_number);
        final EditText mMembersGroup = (EditText) contentView.findViewById(R.id.ed_members_group);
        final EditText mStartNumber = (EditText) contentView.findViewById(R.id.ed_start_number);
        EditText mChannel = (EditText) contentView.findViewById(R.id.ed_channel);
        TextView mEnsure = (TextView) contentView.findViewById(R.id.button_ensure);
        TextView mCancel = (TextView) contentView.findViewById(R.id.button_cancel);

        mEnsure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                window.dismiss();
                mMemberLists.clear();
                String startNumber = mStartNumber.getText().toString().trim();
                String membersGroup = mMembersGroup.getText().toString().trim();

                if (!startNumber.equals("") && !membersGroup.equals("")) {
                    int intStartNumber = Integer.valueOf(startNumber);
                    int intMember = Integer.valueOf(membersGroup);
                    showDialogCode(intStartNumber, intMember);
                }
            }
        });

        mCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                window.dismiss();
            }
        });
    }

    private void showDialogCode(final int intStartNumber, final int intMember) {
        mUiHandler = new UiHandler(getActivity());
        nunber = intStartNumber;
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        View view = inflater.inflate(R.layout.code_alter_dialog_layout, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(view);
        TextView ensure = (TextView) view.findViewById(R.id.alter_dialog_button_ensure);
        mCurrentCode = (TextView) view.findViewById(R.id.tv_current_code);
        mCurrentCode.setText(nunber + "");

        final AlertDialog dialog = builder.create();
        dialog.setView(view, 0, 0, 0, 0);
        dialog.show();

        ensure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null) {
                    dialog.dismiss();
                    for (int i = intStartNumber; i <= (intMember + intStartNumber); i++) {
                        MembersListBeen membersListBeen = new MembersListBeen();
                        if (i == intStartNumber) {
                            membersListBeen.setName("本组");
                        } else {
                            membersListBeen.setName("00" + i);
                        }
                        mMemberLists.add(membersListBeen);
                    }

                    if (mAdapter == null) {
                        mAdapter = new MemberListRecyclerAdapter(getActivity(), mMemberLists);
                    }

                    Log.d("yaofang", "mMemberLists.size()......:" + mMemberLists.size());

                    mAdapter.notifyDataSetChanged();
                    mMemberListTitle.setText("成员列表(" + mMemberLists.size() + ")");
                }
            }
        });

        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                nunber = nunber + 1;
                if(nunber == (intMember + intStartNumber)){
                    timer.cancel();
                }
                mUiHandler.sendEmptyMessage(CHANGER_CURRENT_CODE);
            }
        } , 1000 , 1000);

    }

    private void showDialog(final int position) {
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        View view = inflater.inflate(R.layout.delete_alter_dialog_layout, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(view);
        TextView ensure = (TextView) view.findViewById(R.id.alter_dialog_button_ensure);
        TextView cancel = (TextView) view.findViewById(R.id.alter_dialog_button_cancel);
        final AlertDialog dialog = builder.create();
        dialog.setView(view, 0, 0, 0, 0);
        dialog.show();

        ensure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null) {
                    dialog.dismiss();
                    mMemberLists.remove(position);
                    if (mAdapter == null) {
                        mAdapter = new MemberListRecyclerAdapter(getActivity(), mMemberLists);
                    }

                    mAdapter.notifyDataSetChanged();
                    mMemberListTitle.setText("成员列表(" + mMemberLists.size() + ")");
                }
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });

    }


    private class UiHandler extends Handler {

        private final WeakReference<Activity> activityWeakReference;

        public UiHandler(Activity activity){
            activityWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what){
                case CHANGER_CURRENT_CODE :
                    if(mCurrentCode != null){
                        mCurrentCode.setText(nunber + "");
                    }
                break;
            }
        }
    }
}
